//
//  XLUserAccountViewModel.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/9/5.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit

class XLUserAccountViewModel: NSObject {
    
    //VM对应的模型
    var account: XLUserAccount?
    //单例
    static let sharedModel: XLUserAccountViewModel = XLUserAccountViewModel()
    
    var access_token: String? {
        return account?.access_token
    }
    
    //当前用户是否登录
    var userLogon: Bool{
        //access_token有值, 且没过期
        if account?.access_token != nil && isExpire == false{
            return true
        }
        return false
    }
    
    //是否过期
    var isExpire: Bool {
        //过期时间与当前时间对比
        if let expireDate = account?.expireDate{
            if expireDate.compare(Date()) == .orderedDescending {
                return false
            }
        }
        return true
    }
    
    //第一次登录保存了用户信息, 第二次登录不用输入账号密码, 直接从沙盒中取
    override init() {
        super.init()
        account = self.loadUserAccount()
    }
    
    
    
    
    //获取accessToken
    func loadAccessToken(code: String, completion: @escaping (Bool) -> ()) {
        //请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求的参数
        let params = [
            "client_id": WB_APPKEY,
            "client_secret": WB_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URL
        ]
        //使用afn发起请求
        XLNetworkTools.sharedTools.request(method: .Post, urlString: urlString, parameters: params) { (response, error) in
            
            if response == nil || error != nil {
                print("请求错误\(error)")
                completion(false)
                return
            }
            print(response)
            let dict = response! as! [String: Any]
            //字典转模型
            let account = XLUserAccount(dict: dict)
            //print(account)
            //account.access_token = dict["access_token"]
            
            self.loadUserInfo(account: account, completion: completion)
        }
    }
    
    //获取用户数据
    func loadUserInfo(account: XLUserAccount, completion: @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let param = [
            "access_token": account.access_token ?? "",
            "uid": account.uid ?? ""
        ]
        XLNetworkTools.sharedTools.request(method: .Get, urlString: urlString, parameters: param) { (response, error) in
            if response == nil || error != nil {
                print("请求错误\(error)")
                completion(false)
                return
            }
            //print(response)
            let dict = response! as! [String: Any]
            account.name = dict["name"] as? String
            account.profileImgURL = dict["profile_image_url"] as? String
            
            //进行归档保存
            self.saveUserInfo(account: account)
            //将当前登录成功的用户信息保存到视图模型
            self.account = account
            completion(true)
        }
        
    }
    
    //保存用户信息 -- 归档
    func saveUserInfo(account: XLUserAccount) {
        let fileString = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        NSKeyedArchiver.archiveRootObject(account, toFile: fileString)
        //print(account)
    }
    
    //加载用户信息 -- 解档
    func loadUserAccount() -> XLUserAccount? {
        let file = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        return NSKeyedUnarchiver.unarchiveObject(withFile: file) as? XLUserAccount
    }

}
